macheteYeti / [LWAF] Open Saved Searches

// ==UserScript==
// @name         [LWAF] Open Saved Searches
// @namespace    LWAF
// @license MIT
// @include https://livewellandfully.activehosted.com/app/contacts*
// @include https://livewellandfully.activehosted.com/admin/*
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @require https://raw.githubusercontent.com/phstc/jquery-dateFormat/master/dist/jquery-dateformat.min.js
// @author       macheteYeti
// @description  Opens AC saved searches
// @grant       GM_addStyle
// ==/UserScript==

	GM_addStyle( `
	
		#listWarning{background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); font-weight: bold; float: left; height: 100%; width: 60%; padding: 10px;display:block
		webkit-animation: blinkred 1s infinite;  /* Safari 4+ */
  -moz-animation: blinkred 1s infinite;  /* Fx 5+ */
  -o-animation: blinkred 1s infinite;  /* Opera 12+ */
  animation: blinkred 1s infinite;  /* IE 10+, Fx 29+ */
		}
		
		@-webkit-keyframes blinkred {
		  0%, 49% {
			background-color:#f00;
		  }
		  50%, 100% {
			background-color: #fff;
			color:#000
		  }
		}
	` );
var Arrive=function(e,t,n){"use strict";function r(e,t,n){l.addMethod(t,n,e.unbindEvent),l.addMethod(t,n,e.unbindEventWithSelectorOrCallback),l.addMethod(t,n,e.unbindEventWithSelectorAndCallback)}function i(e){e.arrive=f.bindEvent,r(f,e,"unbindArrive"),e.leave=d.bindEvent,r(d,e,"unbindLeave")}if(e.MutationObserver&&"undefined"!=typeof HTMLElement){var o=0,l=function(){var t=HTMLElement.prototype.matches||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector;return{matchesSelector:function(e,n){return e instanceof HTMLElement&&t.call(e,n)},addMethod:function(e,t,r){var i=e[t];e[t]=function(){return r.length==arguments.length?r.apply(this,arguments):"function"==typeof i?i.apply(this,arguments):n}},callCallbacks:function(e,t){t&&t.options.onceOnly&&1==t.firedElems.length&&(e=[e[0]]);for(var n,r=0;n=e[r];r++)n&&n.callback&&n.callback.call(n.elem,n.elem);t&&t.options.onceOnly&&1==t.firedElems.length&&t.me.unbindEventWithSelectorAndCallback.call(t.target,t.selector,t.callback)},checkChildNodesRecursively:function(e,t,n,r){for(var i,o=0;i=e[o];o++)n(i,t,r)&&r.push({callback:t.callback,elem:i}),i.childNodes.length>0&&l.checkChildNodesRecursively(i.childNodes,t,n,r)},mergeArrays:function(e,t){var n,r={};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);for(n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);return r},toElementsArray:function(t){return n===t||"number"==typeof t.length&&t!==e||(t=[t]),t}}}(),c=function(){var e=function(){this._eventsBucket=[],this._beforeAdding=null,this._beforeRemoving=null};return e.prototype.addEvent=function(e,t,n,r){var i={target:e,selector:t,options:n,callback:r,firedElems:[]};return this._beforeAdding&&this._beforeAdding(i),this._eventsBucket.push(i),i},e.prototype.removeEvent=function(e){for(var t,n=this._eventsBucket.length-1;t=this._eventsBucket[n];n--)if(e(t)){this._beforeRemoving&&this._beforeRemoving(t);var r=this._eventsBucket.splice(n,1);r&&r.length&&(r[0].callback=null)}},e.prototype.beforeAdding=function(e){this._beforeAdding=e},e.prototype.beforeRemoving=function(e){this._beforeRemoving=e},e}(),a=function(t,r){var i=new c,o=this,a={fireOnAttributesModification:!1};return i.beforeAdding(function(n){var i,l=n.target;(l===e.document||l===e)&&(l=document.getElementsByTagName("html")[0]),i=new MutationObserver(function(e){r.call(this,e,n)});var c=t(n.options);i.observe(l,c),n.observer=i,n.me=o}),i.beforeRemoving(function(e){e.observer.disconnect()}),this.bindEvent=function(e,t,n){t=l.mergeArrays(a,t);for(var r=l.toElementsArray(this),o=0;o<r.length;o++)i.addEvent(r[o],e,t,n)},this.unbindEvent=function(){var e=l.toElementsArray(this);i.removeEvent(function(t){for(var r=0;r<e.length;r++)if(this===n||t.target===e[r])return!0;return!1})},this.unbindEventWithSelectorOrCallback=function(e){var t,r=l.toElementsArray(this),o=e;t="function"==typeof e?function(e){for(var t=0;t<r.length;t++)if((this===n||e.target===r[t])&&e.callback===o)return!0;return!1}:function(t){for(var i=0;i<r.length;i++)if((this===n||t.target===r[i])&&t.selector===e)return!0;return!1},i.removeEvent(t)},this.unbindEventWithSelectorAndCallback=function(e,t){var r=l.toElementsArray(this);i.removeEvent(function(i){for(var o=0;o<r.length;o++)if((this===n||i.target===r[o])&&i.selector===e&&i.callback===t)return!0;return!1})},this},s=function(){function e(e){var t={attributes:!1,childList:!0,subtree:!0};return e.fireOnAttributesModification&&(t.attributes=!0),t}function t(e,t){e.forEach(function(e){var n=e.addedNodes,i=e.target,o=[];null!==n&&n.length>0?l.checkChildNodesRecursively(n,t,r,o):"attributes"===e.type&&r(i,t,o)&&o.push({callback:t.callback,elem:i}),l.callCallbacks(o,t)})}function r(e,t){return l.matchesSelector(e,t.selector)&&(e._id===n&&(e._id=o++),-1==t.firedElems.indexOf(e._id))?(t.firedElems.push(e._id),!0):!1}var i={fireOnAttributesModification:!1,onceOnly:!1,existing:!1};f=new a(e,t);var c=f.bindEvent;return f.bindEvent=function(e,t,r){n===r?(r=t,t=i):t=l.mergeArrays(i,t);var o=l.toElementsArray(this);if(t.existing){for(var a=[],s=0;s<o.length;s++)for(var u=o[s].querySelectorAll(e),f=0;f<u.length;f++)a.push({callback:r,elem:u[f]});if(t.onceOnly&&a.length)return r.call(a[0].elem,a[0].elem);setTimeout(l.callCallbacks,1,a)}c.call(this,e,t,r)},f},u=function(){function e(){var e={childList:!0,subtree:!0};return e}function t(e,t){e.forEach(function(e){var n=e.removedNodes,i=[];null!==n&&n.length>0&&l.checkChildNodesRecursively(n,t,r,i),l.callCallbacks(i,t)})}function r(e,t){return l.matchesSelector(e,t.selector)}var i={};d=new a(e,t);var o=d.bindEvent;return d.bindEvent=function(e,t,r){n===r?(r=t,t=i):t=l.mergeArrays(i,t),o.call(this,e,t,r)},d},f=new s,d=new u;t&&i(t.fn),i(HTMLElement.prototype),i(NodeList.prototype),i(HTMLCollection.prototype),i(HTMLDocument.prototype),i(Window.prototype);var h={};return r(f,h,"unbindAllArrive"),r(d,h,"unbindAllLeave"),h}}(window,"undefined"==typeof jQuery?null:jQuery,void 0);
/*

$('.automation-row').each(function(){

    if($(this).find('.automation-campaigns-stats .count').first().text()!="0")$(this).find('.ac_check.automationid.ember-checkbox.ember-view').trigger('click');
});

*/
jQuery.fn.selText = function() {
    var obj = this[0];
    
        var selection = obj.ownerDocument.defaultView.getSelection();
        var range = obj.ownerDocument.createRange();
        range.selectNodeContents(obj);
        selection.removeAllRanges();
        selection.addRange(range);
   
    return this;
}

$(document).ready(function(){
	
	$(document).on('keyup','input[placeholder="Enter new search name here"]',function(){
	
		var nam=$(this).val();
		$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://fitaf570.com/sud/grabSearch.php",data:{type:'nam',nam:nam,seg:new URLSearchParams(window.location.search).get('segmentid')}});
	});
	wins=[];
	if($('#formModal.add-list').length){
	
		console.log('adding warning');
		$('#formModal.add-list .modal-footer').prepend('<a id="listWarning" href="https://www.wrike.com/open.htm?id=839860076" target="_blank">Barbara - remember to follow the process so you don\'t break unsubscribe.</a>');
	}
	$(document).arrive(".modal-wrap",function(){
	
		// console.log('found saved search list');
		
		if(!$('.modal-wrap').hasClass('openers')){
		
			$('#openSavedSearches').remove();
			$('#selectAll').remove();
			$('.modal-body').prepend("<div style='display:flex;justify-content:space-between' id='btns'></div>");
			$('#btns').append('<camp-button id="openSavedSearches"><span class="create">Open All in Tabs</span></camp-button>');
			$('#btns').append('<camp-button id="openSavedSearchesMatches" data-matches="1"><span class="create">Open Matches in Tabs</span></camp-button>');
			$('#btns').append("<select id='catSelector' style='height:38px;font-size:16px;padding:5px'><option value='nono'>Select a type</option>");
			$('#btns').append('<camp-button id="hideSavedSearches" data-type="0"><span class="create" style="background-color:#f00">Hide Selected</span></camp-button>');
			$.ajax({
			
				type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://fitaf570.com/sud/grabSearch.php",data:{type:'check'},
				success:function(d){
				
					var cats=[];
					var embers={};
					$('.modal-wrap tr').each(function(i){
					
						if(i>0){
						
							embers[$(this).find('a').first().text()]=$(this).find('span').last().attr('id').substring(5);
							$(this).remove();
						}
					});
					
					var vals=Object.values(d);
					var keys=Object.keys(d);
					$.each(keys,function(i,v){
					
							var cat=keys[i].split('-')[0];
							if(keys[i] in embers)var nextIns='<tr><td class="text_left"><input type="checkbox" class="selector" style="margin-right:10px;width:17px;height:17px;float:left" data-id="'+vals[i]+'" data-cat="'+cat+'"><a class="missing" data-id="'+vals[i]+'" href="#">'+keys[i]+'</a></td><td><button class="ac_button fright xsmall" data-ember-action="" data-ember-action-'+(embers[keys[i]]-1.0)+'="'+(embers[keys[i]]-1.0)+'"><span id="ember'+embers[keys[i]]+'" class="icon left ember-view"><svg style=""><use xlink:href="#circle-x" fill="" class="icon-circle-x"></use></svg></span> Delete</button></td></tr>';
							else var nextIns='<tr style="background-color:#ccc"><td class="text_left"><input type="checkbox" class="selector" style="margin-right:10px;width:17px;height:17px;float:left" data-id="'+vals[i]+'" data-cat="'+cat+'"><a class="missing" data-id="'+vals[i]+'" href="#">'+keys[i]+'</a></td><td>&nbsp;</button></td></tr>';
							$('.modal-wrap tbody').append(nextIns);
						
						if(!isNaN(cat)&&$.inArray(cat,cats)==-1){
						
							cats.push(cat);
							$('#catSelector').append('<option value="'+cat+'">'+cat+'</option>');
						}
					});
				}
			});
			$('.modal-wrap').addClass('openers');
		}
	});
	
	$(document).on('click','.missing',function(){
	
		var url="https://livewellandfully.activehosted.com/app/contacts?limit=100&segmentid="+$(this).attr('data-id');
		window.open(url,"_blank");
	});
	
	$(document).on('change','#catSelector',function(){
	
		if($(this).val()!='nono')$('.modal-body .ac_lists').find('input[type="checkbox"][data-cat="'+$(this).val()+'"]').prop('checked',true);
	});
	
	$(document).on('click','#hideSavedSearches',function(){
	
		var ids=[];
		$('.selector:checked').each(function(){
		
			ids.push($(this).attr('data-id'));
		});
		
		$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:'https://fitaf570.com/sud/grabSearch.php',data:{type:'hide',ids:ids.join(",")}});
	});
	$("#openSavedSearches").unbind('click');
	$(document).on('click','#openSavedSearches,#openSavedSearchesMatches',function(e){
	
		var btn=$(this);
		e.stopImmediatePropagation();
		var ids=[];
		$('.selector:checked').each(function(){
		
			ids.push($(this).attr('data-id'));
		});
		ids.reverse();
		$(ids).each(function(k,v){
		
			var url="https://livewellandfully.activehosted.com/app/contacts?limit=100&segmentid="+v;
			if(typeof btn.attr('data-matches')!=typeof undefined){
			
				url+="&matches=1";
				$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:'https://fitaf570.com/sud/grabSearch.php',data:{type:'matches',id:v,val:null}});
			}
			wins[k]=window.open(url,"_blank");
			
			/* if(typeof btn.attr('data-matches')!=typeof undefined){
			
				if(wins[k]){
				
					wins[k].onload=function(){
					
						console.log('window loaded, checking for matches');
						$(document).arrive('.camp-Text--heading1',function(){
						
							consle.log('found camp text');
							if($(this).text().indexOf("no contacts that match your search conditions")>-1)wins[k].close();
						});
					}
				}
			} */
		});
		e.preventDefault();
		e.stopPropagation();
		return false;
	});
	
	$(document).on('click','.modal-wrap .ac_lists a',function(e){
	
		var nam=$(this).text();
		var seg=e.target.baseURI;
		$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://fitaf570.com/sud/grabSearch.php",data:{type:'nam',nam:nam,seg:seg}});
	});
	
	var urlParams = new URLSearchParams(window.location.search);
	
	if(typeof urlParams.get('segmentid')!=typeof undefined&&urlParams.get('segmentid')!=null&&urlParams.get('segmentid').length>1){
	
		console.log('found segment');
		var seg=urlParams.get('segmentid');
		// console.log('getting tit');
		
		$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://fitaf570.com/sud/grabSearch.php",data:{type:'tit',seg:seg},success:function(d){
		
			// console.log(d.tit);
			$('title').html(d.tit);
			/* if(d.tit.indexOf('B4')>-1){
			
				// $(document).arrive('.c-Input-field',function(){
				
					// console.log('found conditions search');
					var days=d.tit.split(" B4")[0];
					days=days.replace(" days","").split(" for ")[1];
					days=parseInt(days)+1;
					console.log('setting back '+days+' days');
					
					var today=new Date();
					var dateOffset=(24*60*60*1000)*days;
					today.setTime(today.getTime()-dateOffset);
					console.log(today);
					
					console.log($.format.date(today,"MM/dd/yyyy"));
					setTimeout(()=>{
					
						console.log('clicking in search box');
						$('#textInput-1').trigger('click');
						
						$(document).arrive('.components_segments_input-date__current',function(){
						
							// $(this).find('span').text($.format.date(today,"MM/dd/yyyy"));
							$(this).parent().parent().next().find('span').first().trigger('click');
							setTimeout(()=>{$('.pika-title').prepend($('<span class="pika-label">'+$.format.date(today,"M/d/yyyy")+'</span>'));},1000);
							// $('.pika-prev').trigger('click');
							// $('.pika-select-month').prop('selectedIndex',parseInt($.format.date(today,"M"))-1).trigger('change');
							// $('.pika-select-year').val($.format.date(today,"yyyy")).trigger('change');
							// $('.ember-pikaday-input').val($.format.date(today,"MM/dd/yyyy"));
							
							// $('td').removeClass('is-selected');
							// $('.pika-row').first().prepend($('<td data-day="2" class="is-selected" aria-selected="false"><button class="pika-button pika-day" type="button" data-pika-year="'+$.format.date(today,"yyyy")+'" data-pika-month="'+(parseInt($.format.date(today,"M"))-1)+'" data-pika-day="'+$.format.date(today,"d")+'">'+$.format.date(today,"M/d")+'</button></td>'));
							// $('.pika-day[data-pika-day="'+$.format.date(today,"d")+'"]').parent().addClass('is-selected');
							// setTimeout(()=>{$('.t-SegmentSearch-action').trigger('click');},1500);
						});
					},5000);
					
				// });
			} */
			setTimeout(()=>{$('<h3>'+d.tit+'</h3>').insertAfter($('h2').first());},3000);
			
		}});
		
		$(document).arrive('camp-text',function(){
		
			// console.log('found camp text'+$(this).text());
			if($(this).text().indexOf("no contacts that match your search conditions")==-1){
			
				// console.log('adding  contact opener');
				// $(document).arrive('h3',function(){
				
					$('<camp-button class="contacts_index_subheader_add-contact ml10" id="contactsOpener"><span class="create">Open All in Tabs</span></camp-button>').insertAfter($('.edit-all'));
				// });
			}
		});
		
		$(document).on('click','#contactsOpener',function(){
		
			$('.contacts_index_contact-row').each(function(){
			
				window.open("https://livewellandfully.activehosted.com"+$(this).find('a').first().attr('href'));
			});
		});
	}
	if(typeof urlParams.get('matches')!=typeof undefined&&urlParams.get('matches')!=null&&urlParams.get('matches').length>0){
	
		$(document).arrive('camp-text',function(){
		
			// console.log('found camp text'+$(this).text());
			if($(this).text().indexOf("no contacts that match your search conditions")>-1)window.close();
		});
	}
});